package org.admanager.generalpattern.patterncomposition.plugin.popup.actions;

import java.util.Iterator;

import org.admanager.generalpattern.patterncomposition.plugin.KermetaRunner;
import org.eclipse.core.resources.IFile;
import org.eclipse.emf.common.util.URI;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import fr.irisa.triskell.eclipse.console.EclipseConsole;
import fr.irisa.triskell.eclipse.console.IOConsole;

public class PatternCompositionActionDelegate implements IObjectActionDelegate {
	protected StructuredSelection currentSelection;
    protected IFile patternFile;

	public PatternCompositionActionDelegate() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void run(IAction action) {
		// TODO Auto-generated method stub
		IOConsole console = new EclipseConsole("Kermeta Simulator");
		
		try {			
			
			URI patternURI = URI.createURI(patternFile.getLocationURI()
					.toString());
			
			String sourcePatternUrl = patternURI.toString();
			String targetPatternUrl = patternURI.toString().replace(patternFile.getName(), "Composite" + patternFile.getName());
			
			KermetaRunner.run(sourcePatternUrl, targetPatternUrl, console);
			
		} catch (Throwable e) {
			
			e.printStackTrace();
		}	
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		// TODO Auto-generated method stub
		if (selection instanceof StructuredSelection)
		{
			// the selection should be a single *.ecore file
			currentSelection = (StructuredSelection)selection;
			@SuppressWarnings("unchecked")
			Iterator it = currentSelection.iterator();

			while(it.hasNext()) {
				patternFile = (IFile)it.next();
			}

		}
	}

	@Override
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		// TODO Auto-generated method stub

	}

}
